#include "location.h"

#include <QScriptEngine>

//QTM_USE_NAMESPACE
QScriptValue locationConstructor(QScriptContext *context, QScriptEngine *engine)
{
    int method = 0;
    if(context->argumentCount() == 1)
        method = context->argument(0).toInt32();
    Location *location = new Location(method);
    return engine->newQObject(location, QScriptEngine::ScriptOwnership);
}


Location::Location(int method) :
    m_prevLatitude(0),
    m_prevLongitude(0)
{
    m_source = QtMobility::QGeoPositionInfoSource::createDefaultSource(this);
    if(m_source) {
        switch(method) {
        case 0:
            m_source->setPreferredPositioningMethods(QtMobility::QGeoPositionInfoSource::SatellitePositioningMethods);
            break;
        case 1:
            m_source->setPreferredPositioningMethods(QtMobility::QGeoPositionInfoSource::NonSatellitePositioningMethods);
            break;
        case 2:
            m_source->setPreferredPositioningMethods(QtMobility::QGeoPositionInfoSource::AllPositioningMethods);
            break;
        }

        connect(m_source, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(positionUpdated(QGeoPositionInfo)));
    }
}

void Location::startUpdates()
{
    if (m_source)
        m_source->startUpdates();    
}

void Location::stopUpdates()
{
    if(m_source)
        m_source->stopUpdates();
}

void Location::positionUpdated(const QGeoPositionInfo &info)
{
    QtMobility::QGeoCoordinate geoCoordinate = info.coordinate();
    double latitude = geoCoordinate.latitude();
    double longitude = geoCoordinate.longitude();
    if(latitude != m_prevLatitude || longitude != m_prevLongitude) {
        m_prevLatitude = latitude;
        m_prevLongitude = longitude;
        QDateTime dateTime = info.timestamp();
        emit locationUpdated(QString::number(latitude), QString::number(longitude), dateTime);
    }
}
